/*
 * @Date: 2022-06-19 09:48:54
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-06-30 14:13:48
 * @FilePath: \taro-music-learn\src\pages\packageA\songDetail\index.tsx
 * @Description: something
 */

import LoadingCmp from "@/components/LoadingCmp";
import Lyrics from "@/components/Lyrics";
import MusicSlider from "@/components/MusicSlider";
import RotatePic from "@/components/RotatePic";
import { useSelector } from "@/store/hooks";
import {
  changeCurrentSongBySequence,
  fetchSongDetailInfo,
  toggelStatePlayFlag,
  updateCurrentLyricIndex,
  updateSequence
} from "@/store/playSong";
import { Image, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { useDispatch } from "react-redux";
import { AtIcon } from "taro-ui";
import { reqLikeMusicById } from "@/api/songs";
import { fetchUserLikeMusicList } from "@/store/user";
import "./index.scss";
const index: React.FC = () => {
  const backgroundAudioManager = Taro.getBackgroundAudioManager();
  const dispatch = useDispatch();
  const [progress, setProgress] = useState(0);
  const [isChange, setIsChange] = useState(false);
  const [showRotate, setShowRotate] = useState(true);
  const [isLike, setIsLike] = useState(false);
  const { currentSongState, UserState } = useSelector(state => ({
    currentSongState: state.PlaySong,
    UserState: state.User
  }));
  const currentLyricList = useRef<Array<any>>();
  const duration = currentSongState.currentSong.dt || 0;

  useEffect(() => {
    currentLyricList.current = currentSongState.lyricList;
  }, [currentSongState.lyricList.length]);
  useEffect(() => {
    backgroundAudioManager.onPause(() => {
      dispatch<any>(toggelStatePlayFlag(false));
    });
    backgroundAudioManager.onPlay(() => {
      dispatch<any>(toggelStatePlayFlag(true));
    });
    backgroundAudioManager.onEnded(() => {
      dispatch<any>(changeCurrentSongBySequence(1));
    });
    backgroundAudioManager.onTimeUpdate(() => {
      Taro.getBackgroundAudioPlayerState({
        success(res) {
          if (res.status !== 2) {
            if (!isChange) {
              setProgress(
                (res.currentPosition / backgroundAudioManager.duration) * 100
              );
              getCurrentLyricsIndex(
                res.currentPosition,
                currentLyricList.current
              );
            }
          }
        }
      });
    });
  }, []);
  useEffect(() => {
    const likeFlag = UserState.likeMusicList.some(item => {
      return item === currentSongState.currentSong.id;
    });
    setIsLike(likeFlag);
  }, [currentSongState.currentSong.id]);
  useEffect(() => {
    dispatch<any>(fetchSongDetailInfo(currentSongState.currentSong.id));
    Taro.setNavigationBarTitle({
      title:
        currentSongState.currentSong.name +
        "-" +
        currentSongState.currentSong.ar[0].name
    });
    setCurrentSong();
  }, [currentSongState.timeStamp, currentSongState.currentSong.id]);
  //获取歌词索引
  const getCurrentLyricsIndex = (currentTime, lyricArr) => {
    let lyricsIndex = 0;
    lyricArr.some(item => {
      if (lyricsIndex < lyricArr.length) {
        if (currentTime > item.t) {
          lyricsIndex += 1;
        }
        return currentTime <= item.t;
      }
    });
    dispatch(updateCurrentLyricIndex(lyricsIndex - 1));
  };
  const onChange = e => {
    const { value } = e.detail;
    let currentPosition = Math.floor(((duration / 1000) * value) / 100);
    backgroundAudioManager.seek(currentPosition);
    setIsChange(false);
  };
  const onChanging = useCallback(
    e => {
      setIsChange(true);
    },
    [duration]
  );
  const togglePlayFlag = () => {
    if (currentSongState.isPlaying) {
      backgroundAudioManager.pause();
      dispatch<any>(toggelStatePlayFlag(false));
    } else {
      setCurrentSong();
      dispatch<any>(toggelStatePlayFlag(true));
    }
  };
  const setCurrentSong = () => {
    backgroundAudioManager.coverImgUrl =
      currentSongState.currentSong.al && currentSongState.currentSong.al.picUrl;
    backgroundAudioManager.title =
      currentSongState.currentSong.name && currentSongState.currentSong.name;
    backgroundAudioManager.src = `${currentSongState.currentSong.id &&
      `https://music.163.com/song/media/outer/url?id=${currentSongState.currentSong.id}.mp3`}`;
  };
  //切换循环方式
  const changePlayMode = () => {
    let currentSequence = currentSongState.sequence + 1;
    if (currentSequence > 2) {
      currentSequence = 0;
    }
    dispatch(updateSequence(currentSequence));
  };
  const changeCurrentSong = (tag: number) => {
    if (currentSongState.playList.length === 1) {
      return;
    }
    dispatch<any>(changeCurrentSongBySequence(tag));
  };
  const changeShow = () => {
    setShowRotate(!showRotate);
  };
  const changeLike = async () => {
    if (!UserState.isLogin) {
      Taro.atMessage({
        message: "请先登录",
        type: "error"
      });
      return;
    }
    const flag = isLike ? false : true;
    setIsLike(flag);
    let res = await reqLikeMusicById(currentSongState.currentSong.id, flag);
    console.log(res, "操作结果");
    if (res.data.code === 200) {
      dispatch<any>(fetchUserLikeMusicList(UserState.userInfo.userId));
    }
  };
  return (
    <View id="song-detail-container-unique">
      <LoadingCmp />
      <Image
        src={currentSongState.currentSong.al.picUrl}
        lazyLoad
        className="song-pic"
      ></Image>
      {showRotate ? (
        <View className="rotate-music-pic-container" onClick={changeShow}>
          <RotatePic currentSongInfo={currentSongState.currentSong}></RotatePic>
        </View>
      ) : (
        <View onClick={changeShow}>
          <View className="lyric-contaner">
            <Lyrics
              propLyrArr={currentSongState.lyricList}
              CurrentLyricIndex={currentSongState.currentLyricIndex}
            ></Lyrics>
          </View>
        </View>
      )}
      <View className="slider-container">
        <MusicSlider
          progress={progress}
          onChange={onChange}
          onChanging={onChanging}
        ></MusicSlider>
        <View className="control-btns-container">
          {currentSongState.sequence === 0 ? (
            <AtIcon
              value={"repeat-play"}
              onClick={changePlayMode}
              color="#fff"
            ></AtIcon>
          ) : currentSongState.sequence === 1 ? (
            <AtIcon
              value={"shuffle-play"}
              onClick={changePlayMode}
              color="#fff"
            ></AtIcon>
          ) : (
            <AtIcon
              value={"reload"}
              onClick={changePlayMode}
              color="#fff"
            ></AtIcon>
          )}
          <AtIcon
            value="prev"
            onClick={e => {
              changeCurrentSong(-1);
            }}
            color="#fff"
          ></AtIcon>
          <AtIcon
            value={currentSongState.isPlaying ? "pause" : "play"}
            size="50"
            onClick={togglePlayFlag}
            color="#fff"
          ></AtIcon>
          <AtIcon
            value="next"
            onClick={e => {
              changeCurrentSong(1);
            }}
            color="#fff"
          ></AtIcon>
          <AtIcon
            value="heart-2"
            color={isLike ? "#ff0000" : "#fff"}
            onClick={changeLike}
          ></AtIcon>
        </View>
      </View>
    </View>
  );
};
export default index;
